<template>
  <div class="app-box" id="apply">
    <loading :show="isloading" :text="loadingtex"></loading>
    <step v-show="showStep" v-model="step1" background-color='#fbf9fe'>
      <step-item title="填卡"></step-item>
      <step-item title="资料"></step-item>
      <step-item title="完成"></step-item>
    </step>
    <div class="order-info-box">
      <div class="vux-1px-b" style="padding:9px 0;font-size:16px; color: #333;">订单详情</div>
      <div style="margin-top:10px;">
        <div class="order-info-title inline">商户名称</div>
        <div class="inline">{{cardfrom.merName}}</div>
      </div>
      <div>
        <div class="order-info-title inline">订单编号</div>
        <div class="inline">{{cardfrom.mwOrderId}}</div>
      </div>
      <div>
        <div class="order-info-title inline">订单时间</div>
        <div class="inline">{{tradeDate}}</div>
      </div>
      <div style="padding-bottom:10px;">
        <div class="order-info-title inline">订单金额</div>
        <div class="inline">{{cardfrom.goods_amount}}</div>
      </div>
    </div>
    <group @click.native="hideStep">
      <x-input title="信用卡号" :disabled="creditCardDisabled" @input.native="inputCard" type="tel" placeholder="请输入信用卡号" text-align="right" mask="9999 9999 9999 9999" v-model="cardfrom.cardNo" :max="19" :is-type="isBankCard"></x-input>
      <x-input title="银行名称" disabled placeholder="输入信用卡号后自动获取" text-align="right" v-model="cardfrom.bankName"></x-input>
      <selector ref="qsSelect" @change.native="stageChange" title="分期数" :options="qslist" v-model="cardfrom.stageCount"></selector>
      <cell class="card-explain" style="padding:5px 15px;">手续费率 每月仅需<span>{{eachRate}}</span>%</cell>
    </group>
    <card id="apply-card">
      <div slot="content" class="apply-card-content vux-1px-b">
        <div class="numberfont xxxnum">{{cardfrom.eachPayMoney}}</div>
        <div><span class="export">3期</span> <span class="card-explain">预计每期还款金额(元)</span></div>
      </div>
      <div slot="footer" class="apply-card-footer">
        <flexbox>
          <flexbox-item :span="3.5" class="tc">
            <span class=" ">{{cardfrom.eachGoodsMoney}}</span>
            <br/>
            <span class="card-explain">商品本金(元)</span>
          </flexbox-item>
          <flexbox-item :span="1">
            +
          </flexbox-item>
          <flexbox-item :span="3.5" class="vux-1px-rf tc">
            <span>{{cardfrom.eachInterest}}</span>
            <br/>
            <span class="card-explain">手续费(元)</span>
          </flexbox-item>
          <flexbox-item :span="4" class="tc">
            <img class="calendar-img" src="../assets/calendar.svg">
            <br/>
            <span class="export">扣款计划表</span>
          </flexbox-item>
        </flexbox>
      </div>
    </card>
    <div class="plr" style="padding-top:0px;">
      <x-button type="primary" @click.native="toinfo" :disabled="isnext">下一步</x-button>
    </div>
  </div>
</template>
<script>
import { Group, XInput, XButton, Alert, Cell, Selector, Card, Flexbox, FlexboxItem, Step, StepItem, Loading } from 'vux'
import { getRateInfo, queryOrderIdInfo, installOrderId } from '@/api/apply'
import { cloneObj } from '@/utils/common'
let channelMap = { '12': '01', '24': '01', '6': '01' }
let rateMap = { '12': '0', '24': '18', '6': '0' }
let lowlimitMap = { '12': '600', '24': '600', '6': '600' }
let upLimitMap = { '12': '50000', '24': '50000', '6': '50000' }
export default {
  components: {
    XInput,
    XButton,
    Group,
    Cell,
    Alert,
    Selector,
    Card,
    Flexbox,
    FlexboxItem,
    Step,
    StepItem,
    Loading
  },
  data() {
    return {
      cardfrom: {
        merName: '',
        returnurl: '', // 回跳商城地址
        cardNo: '3568804670613413', // 信用卡号
        bankName: '', // 银行名称
        bankCode: '', // 银行代码
        stageCount: '', // 选定期数
        custRate: '', // 选定费率期数的费率
        channelNo: '', // 渠道号
        merNo: '',
        tooken: '',
        tookenkey: '',
        orderId: '', //不加密orderid
        orderIddes: '', // 加密orderid
        modelType: '',
        goods_amount: '', // 商品金额
        stageAmt: '0', // 支付总额
        eachGoodsMoney: '', // 每期本金
        eachPayMoney: '0.00', // 每期支付金额
        eachInterest: '' // 每期利息
      },
      eachRate: '0.00',
      tradeDate: '',
      qslist: [],
      qsrateData: [],
      // qslist: [{ key: '3', value: '3期' }, { key: '6', value: '6期' }, { key: '12', value: '12期' }, { key: '18', value: '18期' }],
      step1: 0,
      showStep: true,
      amtLowlimit: 0,
      amtUplimit: 0,
      isnext: true,
      creditCardDisabled: false,
      isloading: true,
      loadingtex: '取订单详情'
    }
  },
  created() {
    // this.selectRate()
  },
  mounted() {
    debugger
    this.cardfrom.orderIddes = encodeURIComponent(this.$route.query.orderId)
    this.cardfrom.sign = encodeURIComponent(this.$route.query.sign)
    this.sign = encodeURIComponent(this.$route.query.sign)
    this.getOrderInfo()
    this.selectrtl()
  },
  methods: {
    // 取订单详情

    getOrderInfo() {
      queryOrderIdInfo({ orderId: this.cardfrom.orderIddes, sign: this.$route.query.sign }).then(oidata => {
        console.log(oidata)
        this.isloading = false
        if (oidata.data.code === '0000') {
          var _data = oidata.data.data
          this.cardfrom.merName = _data.merName
          this.cardfrom.merNo = _data.merNo
          this.cardfrom.returnurl = _data.returnurl
          this.cardfrom.tooken = _data.token
          this.tradeDate = _data.tradeDate
          this.cardfrom.mwOrderId = _data.orderId
          this.cardfrom.goods_amount = _data.amount
          this.cardfrom.bankName = _data.bankName
          this.cardfrom.bankCode = _data.bankCode
          this.cardfrom.prdtNo = _data.prdtNo
          if (_data.nper && _data.nper != '') {
            this.stageCount = _data.nper
          }
          if (_data.credCardno) {
            this.isloading = false
            this.cardfrom.cardNo = _data.credCardno
            this.creditCardDisabled = true
            this.selectRate()
          }
        }
        debugger
      }).catch(error => {
        throw error
      })
    },
    // 查费率和期数
    selectRate() {
      // debugger
      var _geRateParams = { cardNo: this.cardfrom.cardNo, orderIdress: this.cardfrom.orderIddes }
      if (this.stageCount && this.stageCount != '') {
        _geRateParams.nper = this.stageCount
      }
      this.isloading = true
      this.loadingtex = '取期数费率'
      getRateInfo(_geRateParams).then(pmidata => {
        console.log('selectRate..............................')
        console.dir(pmidata)
        this.isloading = false
        let midata = pmidata.data
        // debugger
        if (midata.queryRateDto) {

          this.cardfrom.bankCode = midata.queryRateDto.bankCode
          this.cardfrom.bankName = midata.queryRateDto.bankName
          this.handleQishu(midata.queryRateDto)
        } else {
          debugger
          let errormsg = '该信用卡支持该业务'
          if (midata.error_business_response && midata.error_business_response.msg) {
            errormsg = midata.error_business_response.msg
          }
          this.$vux.alert.show({
            title: '提示',
            content: errormsg
          })
        }
      }).catch(error => {
        this.isloading = false
        this.$vux.alert.show({
          title: '提示',
          content: '期数费率取值失败'
        })
        throw error
      })
    },
    // 期数出来
    handleQishu(qsdata) {
      debugger
      this.qslist = []
      this.qsrateData = []
      if (qsdata.nperList instanceof Array) {
        this.qsrateData = qsdata.nperList

      } else if (qsdata.nperList) {
        debugger
        this.qsrateData.push(qsdata.nperList)
      }
      for (let i = 0, l = this.qsrateData.length; i < l; i++) {
        // debugger
        let rateObject = { key: this.qsrateData[i].nper, value: this.qsrateData[i].nper + '期' }
        this.qslist.push(rateObject)
      }
      // 赋值利息map
      // 赋值渠道map
      // 赋值上限map
      // 赋值下限map
      debugger
    },
    // 卡号输入
    inputCard() {
      setTimeout(() => {
        console.log('this.cardfrom.cardNo.......', this.cardfrom.cardNo)
        if (this.cardfrom.cardNo.length === 19) {
          this.selectRate()
        }
      }, 100)
    },
    // 期数改变
    stageChange() {
      setTimeout(() => {
        this.setRate()
        this.computerPayMoney()
      }, 150)
    },
    // 设置费率
    setRate() {
      debugger
      for (var i = 0, l = this.qsrateData.length; i < l; i++) {
        if (this.cardfrom.stageCount == this.qsrateData[i].nper) {
          this.cardfrom.custRate = this.qsrateData[i].rate
          this.cardfrom.channelNo = this.qsrateData[i].channelNo
          this.amtLowlimit = this.qsrateData[i].amtLowlimit
          this.amtUplimit = this.qsrateData[i].amtUplimit
        }
      }
      debugger
    },
    // 查费率和期数
    checkReatSatge() {
      if (this.qslist.length === 0) {
        this.$vux.alert.show({
          title: '提示',
          content: '请输入信用卡号，获取支持的期数'
        })
        this.cardfrom.goods_amount = ''
      }
    },
    // 计算还款总额
    computerPayMoney() {
      debugger
      this.checkReatSatge()
      console.log('computerPayMoney...........')
      // debugger
      setTimeout(function() {
        if (this.cardfrom.stageCount) {
          var goods_amount = 0
          if (this.cardfrom.goods_amount !== '') {
            goods_amount = this.cardfrom.goods_amount
          }
          this.cardfrom.stageAmt = (parseFloat(goods_amount) + parseFloat(goods_amount) * 100 * (parseFloat(this.cardfrom.custRate) * 100) / 1000000 + 0.00001).toFixed(2)
          debugger
          this.computerEachPayMoney()
          this.comuterEachGoodMoney()
          this.comuterEachInterest()
          this.comuterEachRate()
          this.enableNext()
        }
      }.bind(this), 100)
    },
    // 计算每期还款额
    computerEachPayMoney() {
      this.cardfrom.eachPayMoney = (parseFloat(this.cardfrom.stageAmt) * 100 / parseInt(this.cardfrom.stageCount) / 100).toFixed(2)
    },
    // 计算每期本金
    comuterEachGoodMoney() {
      var goods_amount = 0
      if (this.cardfrom.goods_amount !== '') {
        goods_amount = this.cardfrom.goods_amount
      }
      this.cardfrom.eachGoodsMoney = (parseFloat(goods_amount) * 100 / parseInt(this.cardfrom.stageCount) / 100).toFixed(2)
    },
    // 计算每期利息
    comuterEachInterest() {
      this.cardfrom.eachInterest = ((this.cardfrom.eachPayMoney * 100 - this.cardfrom.eachGoodsMoney * 100) / 100).toFixed(2)
    },
    // 每期费率
    comuterEachRate() {
      this.eachRate = (this.cardfrom.custRate * 100 / parseInt(this.cardfrom.stageCount) / 100).toFixed(2)
    },
    // 启用下一步
    enableNext() {
      console.log('sdfsfsdfsa')
      // debugger
      if (this.cardfrom.stageCount && parseFloat(this.amtLowlimit) < parseFloat(this.cardfrom.stageAmt) && parseFloat(this.amtUplimit) > parseFloat(this.cardfrom.stageAmt)) {
        this.isnext = false
      } else {
        this.isnext = true
      }
    },
    // 下一步
    toinfo() {
      // debugger
      this.cardfrom.nper = this.cardfrom.stageCount
      this.cardfrom.totalamount = this.cardfrom.stageAmt
      this.cardfrom.eachMoney = this.cardfrom.eachPayMoney
      this.isloading = true
      this.loadingtex = '提交中'
      installOrderId(this.cardfrom).then(updateorder => {
        this.isloading = false
        debugger
        if (updateorder.data && updateorder.data.tooken) {
          this.cardfrom.tookenkey = updateorder.data.tooken
          this.$router.push({ name: 'info', query: {}, params: this.cardfrom })
        } else {
          this.$router.push({ path: '/tradeResult', query: { errormsg: '无效订单', resultCode: '59', serial_no: this.payCode, returnurl: this.$route.params.returnurl } })
        }
        console.dir(updateorder)
      }).catch(error => {
        this.isloading = false
        this.$vux.alert.show({
          title: '提示',
          content: '订单提交失败'
        })
        debugger
        console.dir(error)
      })
      // this.$router.push({ name: 'info', query: {}, params: this.cardfrom })
    },
    isBankCard(vcard) {
      console.log(vcard)
      var _bcard = vcard.replace(/\D/g, '')
      var _valid = { valid: true }
      if (_bcard.length !== 16) {
        _valid = { valid: false, msg: '信用卡号错误' }
      }
      return _valid
    },
    hideStep() {
      this.showStep = false
    },
    selectrtl() {
      var selects = document.getElementsByTagName('select')
      for (let i = 0, l = selects.length; i < l; i++) {
        selects[i].dir = 'rtl'
      }
    },
    mf() {
      return 2
    }
  }
}

</script>
<style lang="less">
.order-info-box {
  background: #fff;
  color: #8e8b8b;
  font-size: 13px;
  padding: 0px 15px;
  margin-bottom: 15px;
}

.order-info-box div.inline {
  display: inline-block;
  font-size: 13px;
  line-height: 25px;
}

.order-info-title {
  width: 120px;
}

#apply {
  .weui-cells {
    margin-top: 0;
  }
}

.card-flex {
  display: flex;
}

.apply-card-content {
  padding: 20px 10px 10px 10px;
  text-align: center;
  color: #ffffff;
}

.apply-card-footer {
  padding: 15px 20px;
  text-align: center;
  color: #fff;
}

#apply-card {
  border-radius: 5px;
  margin: 15px 15px 15px 15px;
  background: -webkit-linear-gradient(56deg, rgba(83, 182, 242, 1), rgba(87, 152, 238, 1));
  /* Safari 5.1 - 6.0 */
  background: -o-linear-gradient(56deg, rgba(83, 182, 242, 1), rgba(87, 152, 238, 1));
  /* Opera 11.1 - 12.0 */
  background: -moz-linear-gradient(56deg, rgba(83, 182, 242, 1), rgba(87, 152, 238, 1));
  /* Firefox 3.6 - 15 */
  background: linear-gradient(56deg, rgba(83, 182, 242, 1), rgba(87, 152, 238, 1));
  /* 标准的语法 */
}

.apply-card-content.vux-1px-b {
  &:after {
    border-color: rgba(255, 255, 255, 0.6);
    margin: 0 10px;
  }
}

.vux-1px-rf:after {
  border-color: rgba(255, 255, 255, 0.6);
}

.xxxnum {
  font-size: 30px;
}

.calendar-img {
  width: 20px;
}

.card-explain {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.6);
}

#apply {


  .weui-btn:after {
    border-width: 0px;
  }
  .export {
    font-size: 13px;
  }
  .weui-cells:after {
    margin: 0 10px;
  }
  .weui-cell:before {
    margin-right: 10px;
  }
}

</style>
